/**
 * 时长统计组件
 * 
 * 该文件实现了睡眠时长统计功能
 * 包括总持续时长和各个睡眠状态的分别统计
 * 
 * 功能：
 * - 显示总持续时长（hh:mm:ss格式）
 * - 统计各睡眠状态的持续时长
 * - 实时更新时长数据
 * - 可视化时长分布
 * 
 * 原理：
 * - 使用定时器实时更新时长统计
 * - 根据当前用户状态累计各状态时长
 * - 提供格式化的时间显示
 */

package com.example.brain_wave.ui.components

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.BarChart
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay

/**
 * 时长统计数据类
 */
data class DurationStats(
    val totalDuration: Long = 0L,  // 总时长（秒）
    val deepSleepDuration: Long = 0L,  // 深度睡眠时长
    val lightSleepDuration: Long = 0L,  // 浅度睡眠时长
    val drowsyDuration: Long = 0L,  // 困倦状态时长
    val remSleepDuration: Long = 0L,  // REM睡眠时长
    val awakeDuration: Long = 0L  // 清醒时长
) {
    /**
     * 格式化时长为 hh:mm:ss 格式
     */
    fun formatDuration(seconds: Long): String {
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        val secs = seconds % 60
        return String.format("%02d:%02d:%02d", hours, minutes, secs)
    }
    
    /**
     * 获取各状态时长
     */
    fun getStateDuration(userState: UserState): Long {
        return when (userState) {
            UserState.DEEP_SLEEP -> deepSleepDuration
            UserState.LIGHT_SLEEP -> lightSleepDuration
            UserState.DROWSY -> drowsyDuration  // 添加困倦状态
            UserState.REM_SLEEP -> remSleepDuration
            UserState.AWAKE -> awakeDuration
            // 移除UNKNOWN状态处理
        }
    }
    
    /**
     * 获取状态占比
     */
    fun getStatePercentage(userState: UserState): Float {
        if (totalDuration == 0L) return 0f
        return getStateDuration(userState).toFloat() / totalDuration.toFloat()
    }
}

/**
 * 时长统计组件
 */
@Composable
fun DurationStatistics(
    isConnected: Boolean,  // 是否连接设备
    currentUserState: UserState,  // 当前用户状态
    modifier: Modifier = Modifier
) {
    // 统计数据状态
    var durationStats by remember { mutableStateOf(DurationStats()) }
    var lastUpdateTime by remember { mutableStateOf(System.currentTimeMillis()) }
    var currentState by remember { mutableStateOf(currentUserState) }
    
    // 实时更新时长统计
    LaunchedEffect(isConnected, currentUserState) {
        if (isConnected) {
            while (isConnected) {
                val currentTime = System.currentTimeMillis()
                val deltaSeconds = (currentTime - lastUpdateTime) / 1000
                
                if (deltaSeconds > 0) {
                    durationStats = durationStats.copy(
                        totalDuration = durationStats.totalDuration + deltaSeconds,
                        deepSleepDuration = if (currentState == UserState.DEEP_SLEEP) 
                            durationStats.deepSleepDuration + deltaSeconds else durationStats.deepSleepDuration,
                        lightSleepDuration = if (currentState == UserState.LIGHT_SLEEP) 
                            durationStats.lightSleepDuration + deltaSeconds else durationStats.lightSleepDuration,
                        drowsyDuration = if (currentState == UserState.DROWSY) 
                            durationStats.drowsyDuration + deltaSeconds else durationStats.drowsyDuration,
                        remSleepDuration = if (currentState == UserState.REM_SLEEP) 
                            durationStats.remSleepDuration + deltaSeconds else durationStats.remSleepDuration,
                        awakeDuration = if (currentState == UserState.AWAKE) 
                            durationStats.awakeDuration + deltaSeconds else durationStats.awakeDuration
                    )
                    
                    lastUpdateTime = currentTime
                }
                
                currentState = currentUserState
                delay(1000) // 每秒更新一次
            }
        } else {
            // 重置统计数据
            durationStats = DurationStats()
            lastUpdateTime = System.currentTimeMillis()
        }
    }
    
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF2A2A2A)
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 标题
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "时长统计",
                    color = Color.White,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
                
                Icon(
                    imageVector = Icons.Default.Schedule,
                    contentDescription = "时长统计",
                    tint = Color(0xFF2196F3),
                    modifier = Modifier.size(24.dp)
                )
            }
            
            if (!isConnected) {
                // 未连接状态
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFF1A1A1A)
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(24.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "请先连接设备开始统计",
                            color = Color(0xFF666666),
                            fontSize = 14.sp
                        )
                    }
                }
            } else {
                // 总时长显示
                TotalDurationDisplay(
                    durationStats = durationStats,
                    modifier = Modifier.fillMaxWidth()
                )
                
                // 各状态时长统计
                StatesDurationDisplay(
                    durationStats = durationStats,
                    modifier = Modifier.fillMaxWidth()
                )
                
                // 时长分布图表
                DurationChart(
                    durationStats = durationStats,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(120.dp)
                )
            }
        }
    }
}

/**
 * 总时长显示组件
 */
@Composable
private fun TotalDurationDisplay(
    durationStats: DurationStats,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF1A4A3A)
        ),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column {
                Text(
                    text = "总持续时长",
                    color = Color(0xFF4CAF50),
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium
                )
                Text(
                    text = durationStats.formatDuration(durationStats.totalDuration),
                    color = Color.White,
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold
                )
            }
            
            Icon(
                imageVector = Icons.Default.Schedule,
                contentDescription = "总时长",
                tint = Color(0xFF4CAF50),
                modifier = Modifier.size(32.dp)
            )
        }
    }
}

/**
 * 各状态时长显示组件
 */
@Composable
private fun StatesDurationDisplay(
    durationStats: DurationStats,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "各状态时长统计",
            color = Color(0xFFBBBBBB),
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium
        )
        
        UserState.values().forEach { state ->
            StateDurationItem(
                userState = state,
                duration = durationStats.getStateDuration(state),
                percentage = durationStats.getStatePercentage(state),
                formatDuration = durationStats::formatDuration
            )
        }
    }
}

/**
 * 单个状态时长项
 */
@Composable
private fun StateDurationItem(
    userState: UserState,
    duration: Long,
    percentage: Float,
    formatDuration: (Long) -> String
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF1A1A1A)
        ),
        shape = RoundedCornerShape(6.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(12.dp)
                            .clip(androidx.compose.foundation.shape.CircleShape)
                            .background(userState.color)
                    )
                    
                    Text(
                        text = userState.displayName,
                        color = Color.White,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
                
                Column(
                    horizontalAlignment = Alignment.End
                ) {
                    Text(
                        text = formatDuration(duration),
                        color = Color.White,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = "${(percentage * 100).toInt()}%",
                        color = Color(0xFFBBBBBB),
                        fontSize = 12.sp
                    )
                }
            }
            

        }
    }
}

/**
 * 时长分布图表组件
 */
@Composable
private fun DurationChart(
    durationStats: DurationStats,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF1A1A1A)
        ),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.BarChart,
                    contentDescription = "分布图表",
                    tint = Color(0xFF2196F3),
                    modifier = Modifier.size(16.dp)
                )
                Text(
                    text = "时长分布",
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Canvas(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(80.dp)
            ) {
                drawDurationChart(durationStats, size)
            }
        }
    }
}

/**
 * 绘制时长分布图表
 */
private fun DrawScope.drawDurationChart(
    durationStats: DurationStats,
    canvasSize: Size
) {
    if (durationStats.totalDuration == 0L) return
    
    val states = UserState.values()
    val barWidth = canvasSize.width / states.size
    val maxDuration = states.maxOfOrNull { durationStats.getStateDuration(it) } ?: 1L
    
    states.forEachIndexed { index, state ->
        val duration = durationStats.getStateDuration(state)
        val barHeight = if (maxDuration > 0) {
            (duration.toFloat() / maxDuration.toFloat()) * canvasSize.height * 0.8f
        } else 0f
        
        val x = index * barWidth + barWidth * 0.2f
        val y = canvasSize.height - barHeight
        val width = barWidth * 0.6f
        
        // 绘制柱状图
        drawRect(
            color = state.color,
            topLeft = Offset(x, y),
            size = Size(width, barHeight)
        )
    }
}